const wx2 = require('../../utils/common')

Page({
  data: {
    StartText : "开 始 测 试",
    UploadSpeed: "N/A",
    DownloadSpeed: "N/A",
    isTesting: false
  },
 async StartTest() {
   this.setData({
     StartText : "正 在 测 试"
   })
    let download : number = 0
    let upload : number = 0
    let intData = 2500000;
    for (let index = 0; index < 10; index++) {
      let a = await this.Test(intData)
      download += ((intData/125) / a[0])/10
      upload += ((intData/125)) / a[1]/10
      if(a[0] >= 5000 || a[1] >= 4500)intData = 2000000
      if(a[0] <= 1000 && a[1] <= 1200)intData = 5000000
    }
    this.setData({
      DownloadSpeed : download.toFixed(3).slice(0, -1).toString()+"Mbps",
      UploadSpeed : upload.toFixed(3).slice(0,-1).toString() +"Mbps"
    })

    this.setData({
      StartText : "开 始 测 试"
    })
  },
  async Test(intData:number) {
    // 测试下载
    // downland test
    let start = new Date().getTime()
    let data = await wx2.requestSync("https://5gtest.shangdu.com:8080/download?size="+intData+"&r=0.8661664090652565d","GET",null,null)
    let end = new Date().getTime()
    let time = end - start
    // view
    this.view(time,true,intData)

    // upload test
    start = new Date().getTime()
    await wx2.requestSync("https://node-124-47-2-51.speedtest.cn:51090/upload?r=0.047851478077041154", "POST",data, null);
    end = new Date().getTime()
    let uploadTime = end - start;
    this.view(uploadTime,false,intData)
    return [time,uploadTime]
  },
  view(time : number,downloadOrUpload : boolean,intData:number){
    if (time != -1) {
      if (downloadOrUpload) {
        this.setData({
          DownloadSpeed: ((intData/125 / time)).toFixed(3).slice(0, -1).toString()+"Mbps"
        })
      }else{
        this.setData({
          UploadSpeed: ((intData/125) / time).toFixed(3).slice(0, -1).toString()+"Mbps"
        })
      }
    } else {
      if(downloadOrUpload){
        this.setData({
          DownloadSpeed: "请求失败"
        })
      }else{
        this.setData({
          UploadSpeed: "请求失败"
        })
      }
    }
  }
})